from rest_framework import serializers
from goods.models import SKUImage, SKU
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
from django.conf import settings
from celery_tasks.detail_html.tasks import get_detail_html

"""图片表序列化器"""


class ImageSerializer(serializers.ModelSerializer):
    # 关联嵌套序列化返回
    sku = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        # 指定根据那个模型类生成序列化器字段
        model = SKUImage
        # 指定那些字段生成
        fields = ('id', 'image', 'sku')

    # 保存图片\重写拓展类的保存业务逻辑
    def create(self, validated_data):
        # 获取sku_id
        sku_id = self.context['request'].data.get('sku')
        # 获取保存的图片数据
        image_data=validated_data.get('image')
        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 上传图片到fastDFS
        res = client.upload_by_buffer(image_data.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败！！')
        # 获取上传后的路径
        img_url = res['Remote file_id']
        # 保存图片
        image = SKUImage.objects.create(sku_id=sku_id, image=img_url)
        # sku_id = image.sku.id
        # 生成新的详情页页面
        # get_detail_html.delay(sku_id)
        # 返回结果
        return image

    def update(self, instance, validated_data):
        # 获取保存的图片数据
        image_data = validated_data.get('image')
        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FASTDFS_PATH)
        # 上传图片到fastDFS
        res = client.upload_by_buffer(image_data.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败！！')
        # 获取上传后的路径
        img_url = res['Remote file_id']
        # 更新图片路径
        instance.image = img_url
        # 保存
        instance.save()
        # 调用详情页静态化方法
        sku_id = instance.sku.id
        # get_detail_html.delay(sku_id)
        return instance


"""获取SKU商品序列化器"""


class SKUSeriazlier(serializers.ModelSerializer):
    class Meta:
        # 指定根据哪个模型类生成序列化器字段
        model = SKU
        # 指定哪些字段生成
        fields = ('id', 'name')


